package cn.itcast.order.service;

import cn.itcast.order.mapper.OrderMapper;
import cn.itcast.order.pojo.Order;


import com.yangmin.user.api.UserApi;
import com.yangmin.user.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.cloud.client.discovery.DiscoveryClient;

import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;
    // 引入 外部接口
    @Autowired
    private UserApi userApi;

    public Order queryOrderById(Long orderId) {
        // 1.查询订单
        Order order = orderMapper.findById(orderId);
        // 2. 获取订单的关联用户id
        Long userId = order.getUserId();
        // 3. 去远程调用 用户微服务  查询用户信息就可以了
        //底层就是网络编程
        //new Socket("localhost",8081);


        //询问注册中心 我要的用户服务 的ip地址 端口信息呢
        //注意一下 如果注册中心 使用的eureka 名字 会默认转大写
        //List<ServiceInstance> instances = discoveryClient.getInstances("USER-SERVICE");
        //nacos 不会改你的服务的名字
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        ServiceInstance serviceInstance = chooseServer(instances);
//        String host = serviceInstance.getHost();
//        int port = serviceInstance.getPort();

        //User user = restTemplate.getForObject("http://user-service/user/" + userId, User.class);

        // 使用外部接口来进行调用
        User user = userApi.findById(userId);

        // 封装user对象
        order.setUser(user);
        // 4.返回
        return order;
    }

    // 负载均衡
    private ServiceInstance chooseServer(List<ServiceInstance> instances) {
        int i = new Random().nextInt(instances.size());
        ServiceInstance instance = instances.get(i);
        log.info("该次负载到用户服务的host:{},port:{}",instance.getHost(),instance.getPort());
        return instance;
    }
}
